package com.cskaoyan.udp.edition4;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/*
       接收发送方发送的数据
 */
public class ReceiverTask implements Runnable {

    DatagramSocket datagramSocket;

    public ReceiverTask(DatagramSocket datagramSocket) {
        this.datagramSocket = datagramSocket;
    }

    @Override
    public void run() {
        // 用于接收数据的数据报包
        byte[] bytes = new byte[1024];
        DatagramPacket receivePacket = new DatagramPacket(bytes, 0, bytes.length);

        boolean flag = true;

        try {
            while (flag) {
                // 接收发送端发送的数据
               datagramSocket.receive(receivePacket);

               // 解析接收到的数据
                byte[] data = receivePacket.getData();
                int offset = receivePacket.getOffset();
                int length = receivePacket.getLength();

                String result = new String(data, offset, length);
                // 获取发送方ip地址
                InetAddress address = receivePacket.getAddress();
                int port = receivePacket.getPort();
                System.out.println(address + "-" + port + ": " + result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
